package com.mollytask.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.mollytask.MainActivity;
import com.mollytask.R;
import com.mollytask.bean.Institution;
import com.mollytask.bean.MyUser;
import com.mollytask.bean.SuperAdmin;
import com.mollytask.util.DialogUtils;
import com.mollytask.util.RegexUtil;

import java.util.List;

import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

    private ImageView mReturnIv;
    private EditText register_et_phone;
    private EditText register_et_code;
    private EditText register_et_password;
    private Button register_btn_finish;
    private Button register_btn_getCode;

    private Boolean hasCode = false;
    private Boolean hasPassword = false;

    private Handler mHandler;
    private static final int VERIFY_TIME = 60;
    private int time = VERIFY_TIME;
    private static final int COUNT = 1;

    String phone, code, password;


    private EditText mInCode, mInName, mInType, mInAdress, mInZipCode, mInFaxPhone, mInEmail, mInPricipal, mInSuperAccount;
    private EditText mSuCode, mSuName, mSuDepartName, mSuAdress, mSuPostCode, mSuDirector;

    private TextView mInPositive;
    private TextView mSuPositive;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_register);

        findId();
        setListener();
    }


    private void setListener() {
        mReturnIv.setOnClickListener(this);
        register_btn_getCode.setOnClickListener(this);
        register_et_code.setOnFocusChangeListener(this);
        register_et_password.setOnFocusChangeListener(this);
        register_et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (RegexUtil.checkMobile(charSequence.toString())) {
                    register_btn_getCode.setClickable(true);
                    register_btn_getCode.setBackground(getResources().getDrawable(R.drawable.btn_send_y));
                    register_btn_getCode.setTextColor(getResources().getColor(R.color.send_color_y));
                } else {
                    register_btn_getCode.setClickable(false);
                    register_btn_getCode.setBackground(getResources().getDrawable(R.drawable.btn_send));
                    register_btn_getCode.setTextColor(getResources().getColor(R.color.send_color_n));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        register_et_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                hasCode = charSequence.length() != 0;
                if (hasPassword & hasCode) {
                    register_btn_finish.setBackground(getResources().getDrawable(R.drawable.bg_btn_y));
                    register_btn_finish.setClickable(true);
                } else {
                    register_btn_finish.setBackground(getResources().getDrawable(R.drawable.bg_btn));
                    register_btn_finish.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        register_et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                hasPassword = charSequence.length() != 0;
                if (hasPassword & hasCode) {
                    register_btn_finish.setBackground(getResources().getDrawable(R.drawable.bg_btn_y));
                    register_btn_finish.setClickable(true);
                } else {
                    register_btn_finish.setBackground(getResources().getDrawable(R.drawable.bg_btn));
                    register_btn_finish.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        register_btn_finish.setOnClickListener(this);
    }

    private void findId() {
        mReturnIv = (ImageView) findViewById(R.id.register_iv_return);
        register_et_phone = (EditText) findViewById(R.id.register_et_phone);
        register_et_code = (EditText) findViewById(R.id.register_et_code);
        register_et_password = (EditText) findViewById(R.id.register_et_password);
        register_btn_finish = (Button) findViewById(R.id.register_btn_finish);
        register_btn_getCode = (Button) findViewById(R.id.register_btn_getcode);
    }

    @Override
    public void onClick(View view) {
        phone = register_et_phone.getText().toString().trim();
        switch (view.getId()) {
            //返回按钮
            case R.id.register_iv_return:
                finish();
                break;
            //验证码
            case R.id.register_btn_getcode:
                phone = register_et_phone.getText().toString().trim();
                beginCount();
                sendCode();
                break;
            //注册按钮
            case R.id.register_btn_finish:

                phone = register_et_phone.getText().toString().trim();
                code = register_et_code.getText().toString().trim();
                password = register_et_password.getText().toString().trim();
                if (!checkPassLength()) {
                    DialogUtils.showToast(RegisterActivity.this, "密码长度为6-16位");
                    break;
                }

//                BmobQuery<MyUser> bmobQuery = new BmobQuery<>();
//                bmobQuery.addWhereEqualTo("username", phone);
//                bmobQuery.findObjects(new FindListener<MyUser>() {
//                    @Override
//                    public void done(List<MyUser> list, cn.bmob.v3.exception.BmobException e) {
//                        if (list.size() > 0) {
//                            DialogUtils.showToast(RegisterActivity.this, "该帐号已经注册过了");
//                        } else {
                register();

//                        }
//                    }
//                });

                break;
        }
    }

    private void register() {

        BmobUser.signOrLoginByMobilePhone(phone, code, new LogInListener<MyUser>() {
            @Override
            public void done(MyUser myUser, cn.bmob.v3.exception.BmobException e) {
                if (e == null) {

                    new MaterialDialog.Builder(RegisterActivity.this)
                            .title("请选择用户类型")
                            .items(new String[]{"公共机构", "上级行政部门", "天津市能源管理局"})
                            .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
                                @Override
                                public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                    if (which == 0) {
                                        showInstitutionDialog();
                                    } else if (which == 1) {
                                        showSuperAdminDialog();
                                    } else if (which == 2) {
                                        showEnergyDialog();
                                    }
                                    return true;
                                }
                            })
                            .positiveText("确定")
                            .canceledOnTouchOutside(false)
                            .show();

                } else {
                    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void sendCode() {
        BmobSMS.requestSMSCode(RegisterActivity.this, phone, "手机号码", new RequestSMSCodeListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    DialogUtils.showToast(RegisterActivity.this, "发送成功");
                } else {
                    DialogUtils.showToast(RegisterActivity.this, e.getMessage().toString());
                }
            }
        });

    }

    private boolean checkPassLength() {
        return password.length() >= 6 & password.length() <= 16;
    }

    //开始倒计时
    private void beginCount() {
        register_btn_getCode.setBackground(getResources().getDrawable(R.drawable.btn_send));
        register_btn_getCode.setTextColor(getResources().getColor(R.color.send_color_n));
        register_btn_getCode.setClickable(false);
        if (mHandler == null) {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (time > 0) {
                        register_btn_getCode.setText(time + "");
                        mHandler.sendEmptyMessageDelayed(COUNT, 1000);
                        time--;
                    } else {
                        register_btn_getCode.setText("发送");
                        register_btn_getCode.setClickable(true);
                        register_btn_getCode.setBackground(getResources().getDrawable(R.drawable.btn_send_y));
                        register_btn_getCode.setTextColor(getResources().getColor(R.color.send_color_y));
                        time = 60;
                    }
                }
            };
        }
        mHandler.sendEmptyMessage(1000);
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        code = register_et_code.getText().toString().trim();
        phone = register_et_phone.getText().toString().trim();
        switch (view.getId()) {
            case R.id.register_et_code:
                if (b) {
                    if (phone.equals("")) {
                        DialogUtils.showToast(RegisterActivity.this, "请输入手机号码");
                    } else {
                        if (!RegexUtil.checkMobile(phone)) {
                            DialogUtils.showToast(RegisterActivity.this, "无效的手机号码");
                        }
                    }
                }
                break;
            case R.id.register_et_password:
                if (b) {
                    if (phone.equals("")) {

                        com.mollytask.util.DialogUtils.showToast(RegisterActivity.this, "请输入手机号码");
                    } else if (code.equals("")) {
                        DialogUtils.showToast(RegisterActivity.this, "请输入验证码");
                    } else {
                        if (!RegexUtil.checkMobile(phone)) {
                            DialogUtils.showToast(RegisterActivity.this, "无效的手机号码");
                        }
                    }
                }
                break;
        }
    }

    //显示完善公共机构信息对话框
    private void showInstitutionDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("公共机构信息完善")
                .customView(R.layout.view_institution, true)
                .canceledOnTouchOutside(false)
                .show();
        View view = dialog.getView();
        mInAdress = (EditText) view.findViewById(R.id.address);
        mInCode = (EditText) view.findViewById(R.id.code);
        mInEmail = (EditText) view.findViewById(R.id.email);
        mInName = (EditText) view.findViewById(R.id.name);
        mInFaxPhone = (EditText) view.findViewById(R.id.faxPhone);
        mInPricipal = (EditText) view.findViewById(R.id.principal);
        mInSuperAccount = (EditText) view.findViewById(R.id.superAccount);
        mInZipCode = (EditText) view.findViewById(R.id.zipCode);
        mInType = (EditText) view.findViewById(R.id.type);

        mInPositive = (TextView) view.findViewById(R.id.in_positive);

        mInPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean cancel = false;

                if (TextUtils.isEmpty(mInAdress.getText().toString())
                        || TextUtils.isEmpty(mInCode.getText().toString())
                        || TextUtils.isEmpty(mInEmail.getText().toString())
                        || TextUtils.isEmpty(mInZipCode.getText().toString())
                        || TextUtils.isEmpty(mInPricipal.getText().toString())
                        || TextUtils.isEmpty(mInType.getText().toString())
                        || TextUtils.isEmpty(mInSuperAccount.getText().toString())
                        || TextUtils.isEmpty(mInFaxPhone.getText().toString())
                        || TextUtils.isEmpty(mInName.getText().toString())) {
                    cancel = true;
                    Toast.makeText(RegisterActivity.this, "请输入完整信息", Toast.LENGTH_LONG).show();
                } else if (mInCode.getText().length() != 9) {
                    Toast.makeText(RegisterActivity.this, "公共机构代码为9位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                } else if (!RegexUtil.checkEmail(mInEmail.getText().toString())) {
                    Toast.makeText(RegisterActivity.this, "邮箱无效", Toast.LENGTH_LONG).show();
                    cancel = true;
                } else if (mInZipCode.getText().length() != 6) {
                    Toast.makeText(RegisterActivity.this, "邮政编码为6位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                }

                BmobQuery<SuperAdmin> query = new BmobQuery<>();
                query.addWhereEqualTo("mSuNo", mInSuperAccount.getText().toString());
                boolean finalCancel = cancel;
                query.findObjects(new FindListener<SuperAdmin>() {
                    @Override
                    public void done(List<SuperAdmin> list, cn.bmob.v3.exception.BmobException e) {

                        if (e == null) {
                            //如果可以查询到上级行政部门表中存在
                            if (list.size() > 0) {
                                if (!finalCancel) {
                                    Institution institution = new Institution();
                                    institution.setmInCode(mInCode.getText().toString());
                                    institution.setmInName(mInName.getText().toString());
                                    institution.setmInType(mInType.getText().toString());
                                    institution.setmInAddress(mInAdress.getText().toString());
                                    institution.setmInEmail(mInEmail.getText().toString());
                                    institution.setmPhoneNumber(phone);
                                    institution.setmInPostCode(mInZipCode.getText().toString());
                                    institution.setmInPaxPhone(mInFaxPhone.getText().toString());
                                    institution.setmInDirector(mInPricipal.getText().toString());
                                    institution.setmInSuperAccount(mInSuperAccount.getText().toString());

                                    //上传对象
                                    institution.save(new SaveListener<String>() {
                                        @Override
                                        public void done(String s, cn.bmob.v3.exception.BmobException e) {
                                            Toast.makeText(RegisterActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                                        }
                                    });
                                    saveUser(0, mInCode.getText().toString());
                                }

                            } else {
                                DialogUtils.showToast(RegisterActivity.this, "该上级行政编号不存在");

                            }
                        }
                    }
                });

            }
        });

    }


    //显示完善上级行政部门信息对话框
    private void showSuperAdminDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("上级行政部门信息完善")
                .customView(R.layout.view_super_admin, true)
                .canceledOnTouchOutside(false)
                .show();
        View view = dialog.getView();
        mSuAdress = (EditText) view.findViewById(R.id.super_address);
        mSuCode = (EditText) view.findViewById(R.id.super_code);
        mSuName = (EditText) view.findViewById(R.id.super_name);
        mSuDepartName = (EditText) view.findViewById(R.id.super_depart_name);
        mSuDirector = (EditText) view.findViewById(R.id.super_director);
        mSuPostCode = (EditText) view.findViewById(R.id.super_postCode);
        mSuPositive = (TextView) view.findViewById(R.id.positive);

        mSuPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean cancel = false;

                if (TextUtils.isEmpty(mSuCode.getText().toString())
                        || TextUtils.isEmpty(mSuPostCode.getText().toString())
                        || TextUtils.isEmpty(mSuDirector.getText().toString())
                        || TextUtils.isEmpty(mSuName.getText().toString())
                        || TextUtils.isEmpty(mSuAdress.getText().toString())
                        || TextUtils.isEmpty(mSuDepartName.getText().toString())) {
                    cancel = true;
                    Toast.makeText(RegisterActivity.this, "请输入完整信息", Toast.LENGTH_LONG).show();
                } else if (mSuCode.getText().length() != 9) {
                    Toast.makeText(RegisterActivity.this, "机构代码为9位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                } else if (mSuPostCode.getText().length() != 6) {
                    Toast.makeText(RegisterActivity.this, "邮政编码为6位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                }
                if (!cancel) {

                    SuperAdmin superAdmin = new SuperAdmin();


                    superAdmin.setmSuNo(mSuCode.getText().toString());
                    superAdmin.setmSuPhone(mSuName.getText().toString());
                    superAdmin.setmSuDepartName(mSuDepartName.getText().toString());
                    superAdmin.setmSuAdress(mSuAdress.getText().toString());
                    superAdmin.setmSuPostCode(mSuPostCode.getText().toString());
                    superAdmin.setmSuDirector(mSuDirector.getText().toString());

                    //上传对象
                    superAdmin.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, cn.bmob.v3.exception.BmobException e) {
                            Toast.makeText(RegisterActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                        }
                    });

                    saveUser(1, mSuCode.getText().toString());
                }
            }
        });
    }


    //显示完善公共机构信息对话框
    private void showEnergyDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("能管局信息完善")
                .customView(R.layout.view_energy, true)
                .canceledOnTouchOutside(false)
                .show();
        View view = dialog.getView();
        mInAdress = (EditText) view.findViewById(R.id.address);
        mInCode = (EditText) view.findViewById(R.id.code);
        mInEmail = (EditText) view.findViewById(R.id.email);
        mInName = (EditText) view.findViewById(R.id.name);
        mInFaxPhone = (EditText) view.findViewById(R.id.faxPhone);
        mInPricipal = (EditText) view.findViewById(R.id.principal);
        mInZipCode = (EditText) view.findViewById(R.id.zipCode);
        mInType = (EditText) view.findViewById(R.id.type);

        mInPositive = (TextView) view.findViewById(R.id.in_positive);

        mInPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean cancel = false;

                if (TextUtils.isEmpty(mInAdress.getText().toString())
                        || TextUtils.isEmpty(mInCode.getText().toString())
                        || TextUtils.isEmpty(mInEmail.getText().toString())
                        || TextUtils.isEmpty(mInZipCode.getText().toString())
                        || TextUtils.isEmpty(mInPricipal.getText().toString())
                        || TextUtils.isEmpty(mInType.getText().toString())
                        || TextUtils.isEmpty(mInFaxPhone.getText().toString())
                        || TextUtils.isEmpty(mInName.getText().toString())) {
                    cancel = true;
                    Toast.makeText(RegisterActivity.this, "请输入完整信息", Toast.LENGTH_LONG).show();
                } else if (mInCode.getText().length() != 9) {
                    Toast.makeText(RegisterActivity.this, "公共机构代码为9位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                } else if (!RegexUtil.checkEmail(mInEmail.getText().toString())) {
                    Toast.makeText(RegisterActivity.this, "邮箱无效", Toast.LENGTH_LONG).show();
                    cancel = true;
                } else if (mInZipCode.getText().length() != 6) {
                    Toast.makeText(RegisterActivity.this, "邮政编码为6位数", Toast.LENGTH_LONG).show();
                    cancel = true;
                }

                if (!cancel) {

                    Institution institution = new Institution();
                    institution.setmInCode(mInCode.getText().toString());
                    institution.setmInName(mInName.getText().toString());
                    institution.setmInType(mInType.getText().toString());
                    institution.setmInAddress(mInAdress.getText().toString());
                    institution.setmInEmail(mInEmail.getText().toString());
                    institution.setmPhoneNumber(phone);
                    institution.setmInPostCode(mInZipCode.getText().toString());
                    institution.setmInPaxPhone(mInFaxPhone.getText().toString());
                    institution.setmInDirector(mInPricipal.getText().toString());
                    //上传对象
                    institution.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, cn.bmob.v3.exception.BmobException e) {
                            Toast.makeText(RegisterActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                        }
                    });

                    saveUser(2, mInCode.getText().toString());
                }
            }

        });

    }


    //保存用户对象

    private void saveUser(int which, String code) {
        MyUser newUser = new MyUser();
        newUser.setType(which);
        newUser.setUsername(phone);
        newUser.setPassword(password);
        newUser.setCode(code);
        BmobUser bmobUser = BmobUser.getCurrentUser(MyUser.class);
        newUser.update(bmobUser.getObjectId(), new UpdateListener() {
            @Override
            public void done(cn.bmob.v3.exception.BmobException e) {
                if (e == null) {
                    Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    WelcomeActivity.mActivity.finish();

                } else {

                }
            }

        });

    }


}
